package spring.boot.es.controller;

import com.alibaba.fastjson.JSONObject;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Date;

/**
 * https://www.elastic.co/guide/en/elasticsearch/client/java-rest/6.8/java-rest-high-getting-started-maven.html
 */
@RestController
@RequestMapping("/books")
public class BookController {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    RestHighLevelClient highLevelClient;

    String index ="book";

    @PostMapping("/add")
    public Integer add(@RequestParam String title
                           ) throws Exception{
        Book book = new Book();
        book.setId(System.currentTimeMillis()+"");
        book.setTitle(title);
        book.setAuthor("lilui");
        book.setPrice(10);
        book.setMakeDate(new Date());
        try {

            IndexRequest indexRequest = new IndexRequest(index,"_doc").source(JSONObject.toJSONString(book), XContentType.JSON);

           /* highLevelClient.index(indexRequest, RequestOptions.DEFAULT);
            log.info("GrayScaleFunction save log success");*/

            // 异步方法有问题
            highLevelClient.indexAsync(indexRequest, RequestOptions.DEFAULT, new ActionListener<IndexResponse>() {
                @Override
                public void onResponse(IndexResponse indexResponse) {
                    log.info("GrayScaleFunction save log success",JSONObject.toJSONString(indexResponse));
                }

                @Override
                public void onFailure(Exception e) {
                    log.error("GrayScaleFunction save log error:{}"+e);
                }
            });
        } catch (RuntimeException e) {
            log.error("GrayScaleFunction save log error:{}",e);
        }

        return 1;
    }


}
